package mqigdcom.mqigd.ui;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import mqigdcom.mqigd.CustomApp;
import mqigdcom.mqigd.R;
import mqigdcom.mqigd.updatemanager.UpdateManager;
import mqigdcom.mqigd.utils.LogUtils;
import mqigdcom.mqigd.utils.Utils;

/**
 * 主界面（加载网页）
 */
public class MainWebActivity extends BaseActivity {

    private WebView mWebView;// 网页加载器
//    protected static final String HTTP_DOMAIN = "47.110.74.89:20015";// 存储cookie的对应的域名  广东
//    protected static final String HTTP_DOMAIN = "182.43.234.120:7011";// 存储cookie的对应的域名  182贵州
//    protected static final String HTTP_DOMAIN = "113.125.120.7:7011";// 存储cookie的对应的域名  113贵州
    protected static final String HTTP_DOMAIN = "106.39.56.34:7020";// 存储cookie的对应的域名  陕西
//    protected static final String HTTP_DOMAIN = "106.39.56.36:7011";// 存储cookie的对应的域名  贵阳
    //    protected static final String HTTP_DOMAIN = "172.16.210.29:8888";// 存储cookie的对应的域名
    private final String mBaseUrl = "http://" + HTTP_DOMAIN;// + ":82";
    private final String mUrlPathLogin = "/#/login";//
    private final String mUrlPathIndex = "/#/index";// 首页的访问路径
    private final String mUrlPathInvestigation = "/#/investigation";// 路况调查页面的访问路径
    private long mLastClickBackTimestamp;// 上一次点击返回键的时间戳
    private boolean mFlagLoadError;// 页面是否加载出错
    //    private final int mReqGPSSettingsCode = 10;// 请求GPS设置的标识码
//    private final int mReqLocationPermissionCode = 11;// 请求定位的标识码
    public final int mReqStoragePermissionCode = 12;// 请求访问存储卡的权限标识码
    protected boolean mFlagEnteredRoadConditionSearch;// 是否进入了“路况分布”的搜索页面
    //    private LocationManager mLocationManager;// 系统定位的管理器，为了判断GPS定位是否可用
//    private LocationClient mLocationClient;// 百度地图的定位类
//    private CustomBDLocationListener mBDLocationListener;// 百度地图的位置监听器
//    private CustomLocationDialog mLocationDialog;// 定位的弹出框
    protected boolean mFlagAutoCloseLoading = true;// 自动关闭加载框
    private HtmlJsInteraction mHtmlJsInteraction;// Html与本地Js的交互类
    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initWebView();
        if (Utils.isNetworkAvailable(this)) {
            mWebView.loadUrl(mBaseUrl);
        } else {
            mFlagLoadError = true;
            setLoadErrorVisible(true);
            mWebView.setVisibility(View.GONE);
        }
        if (checkStoragePermissions()) {

        } else {
//            new UpdateManager(this, "main").checkUpdate();   //检查更新
        }
    }

    @Override
    protected View createContentView() {
        mWebView = new WebView(this);
        return mWebView;
    }

    @Override
    protected void handleClickedErrorView() {
        if (Utils.isNetworkAvailable(this)) {
            String url = mWebView.getUrl();
            if (TextUtils.isEmpty(url)) {
                url = mBaseUrl;
            }
            mWebView.loadUrl(url);
            mFlagLoadError = false;
            setLoadErrorVisible(false);
        } else {
            showToast(getString(R.string.network_not_available_and_check_to_retry), Toast.LENGTH_SHORT, Gravity.BOTTOM);
        }
    }

    /**
     * 初始化WebView
     */
    private void initWebView() {
//        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);// 设置WebView暂时关闭硬件加速
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mHtmlJsInteraction = new HtmlJsInteraction(this);
        mWebView.addJavascriptInterface(mHtmlJsInteraction, "mqiApp");
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setGeolocationEnabled(true);
//        String ua = webSettings.getUserAgentString();
//        LogUtils.d(TAG, "UA = " + ua);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webSettings.setLoadsImagesAutomatically(true);
        } else {
            webSettings.setLoadsImagesAutomatically(false);
        }
        mWebView.setWebChromeClient(new CustomWebChromeClient());
        mWebView.setWebViewClient(new CustomWebViewClient());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.setWebContentsDebuggingEnabled(true);
        }
    }

    /**
     * 检测访问存储卡的权限
     *
     * @return true 需要申请权限；false 已经获得权限
     */
    private boolean checkStoragePermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        mReqStoragePermissionCode);
                return true;
            }
        }
        return false;
    }

//    /**
//     * 检测定位服务的权限
//     *
//     * @return true 需要申请权限；false 已经获得权限
//     */
//    private boolean checkLocationPermissions() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
//                    ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
//                        Manifest.permission.ACCESS_FINE_LOCATION}, mReqLocationPermissionCode);
//                return true;
//            }
//        }
//        return false;
//    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (mReqGPSSettingsCode == requestCode) {
//            getCurrentLocation();
//        }
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mReqStoragePermissionCode == requestCode) {
            if (permissions.length >= 2 && grantResults.length >= 2) {
                if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permissions[0]) && grantResults[0] != PackageManager.PERMISSION_GRANTED
                        || Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissions[1]) && grantResults[1] != PackageManager.PERMISSION_GRANTED) {
                    showToast(getString(R.string.storage_permission_denied_tips), Toast.LENGTH_SHORT, Gravity.BOTTOM);
                } else {
                    new UpdateManager(this, "main").checkUpdate();   //检查更新
                }
            }
        }
//        else if (mReqLocationPermissionCode == requestCode) {
//            if (permissions.length >= 2 && grantResults.length >= 2) {
//                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permissions[0]) && grantResults[0] != PackageManager.PERMISSION_GRANTED ||
//                        Manifest.permission.ACCESS_FINE_LOCATION.equals(permissions[1]) && grantResults[1] != PackageManager.PERMISSION_GRANTED) {
//                    showToast(R.string.location_permission_denied_tips);
//                } else {
//                    getCurrentLocation();
//                }
//            }
//        }
    }

    /**
     * 加载本地的数据同步页面
     */
    protected void loadLocalData() {
        mWebView.loadUrl("file:///android_asset/html/html/dataNonet.html");
    }

    /**
     * 加载本地的路况调查页面
     */
    protected void loadLocalRoadSurvey() {
        mWebView.loadUrl("file:///android_asset/html/html/index.html");
    }

    /**
     * 返回上一页
     */
    protected void goBackPage() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        }
    }

    private class CustomWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            Log.e("测试", newProgress + "");
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            LogUtils.e(TAG, "onReceivedTitle() title = " + Utils.checkNull(title));
            // android 6.0 以下通过title获取
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                if (title.contains("404") || title.contains("500") || title.contains("Error")) {
                    mFlagLoadError = true;
                }
            }
        }
    }

    private class CustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            LogUtils.d(TAG, "shouldOverrideUrlLoading() url = " + url);
            if (url.endsWith(".pdf")) {
                startActivity(new Intent(MainWebActivity.this, PDFViewActivity.class).putExtra("pdf_url", url));
            } else {
                view.loadUrl(url);
            }
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            LogUtils.d(TAG, "onPageStarted() url = " + url);
            mFlagAutoCloseLoading = true;
            setLoadingVisible(true);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Log.e("测试", "完成onPageFinished");
            if (url.startsWith(mBaseUrl + "/#/distribution")) {// “路况分布”页面为横屏
                if (Utils.checkScreenOrientation(MainWebActivity.this)) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            } else {// 其他页面均为竖屏
                if (!Utils.checkScreenOrientation(MainWebActivity.this)) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
                if (url.startsWith(mBaseUrl + mUrlPathIndex) || url.startsWith(mBaseUrl + mUrlPathLogin)) {// 首页和登录页面
                    mWebView.clearHistory();
                }
            }
            if (mWebKeyboardListener != null) {// 处理软键盘遮挡的问题
                if (url.startsWith(mBaseUrl + mUrlPathLogin)) {
                    mWebKeyboardListener.disableResizeView();
                } else {
                    mWebKeyboardListener.enableResizeView();
                }
            }
//            if (!url.startsWith(mBaseUrl + mUrlPathInvestigation) && !url.endsWith("/html/index.html")) {// 路况调查页面（在线，离线）
//                removeLocationListener();
//            }
            if (!mWebView.getSettings().getLoadsImagesAutomatically()) {
                mWebView.getSettings().setLoadsImagesAutomatically(true);
            }
            if (mFlagAutoCloseLoading) {
                setLoadingVisible(false);
            }
            if (mFlagLoadError) {
                mFlagLoadError = false;
                setLoadErrorVisible(true);
                mWebView.setVisibility(View.GONE);
            } else {
                setLoadErrorVisible(false);
                mWebView.setVisibility(View.VISIBLE);
            }
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    String url = mWebView.getUrl();
                    if (url.startsWith(mBaseUrl + mUrlPathIndex) || url.startsWith(mBaseUrl + mUrlPathLogin)) {// 首页和登录页面
                        setCustomStatusBarVisible(false);
                    } else {
                        setCustomStatusBarVisible(true);
                    }
                }
            }, 200);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            LogUtils.e(TAG, "onReceivedError() url = " + failingUrl + ", errorCode = " + errorCode + ", description = " + description);
            mFlagLoadError = true;
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            int statusCode = errorResponse.getStatusCode();
            LogUtils.e(TAG, "onReceivedHttpError() url = " + request.getUrl() + ", code = " + statusCode);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 页面强制刷新，以重新适应宽度
        mWebView.reload();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isLoadingVisible()) {
                mFlagAutoCloseLoading = true;
                setLoadingVisible(false);
            }
            if (mFlagEnteredRoadConditionSearch) {
                mFlagEnteredRoadConditionSearch = false;
                mWebView.loadUrl("javascript: diply();");
                return true;
            }
            if (mWebView.canGoBack()) {
                if (mWebView.getUrl().startsWith(mBaseUrl + mUrlPathInvestigation)) {// 路况调查页面
                    mWebView.loadUrl(mBaseUrl + mUrlPathIndex + "?timeStamp=" + System.currentTimeMillis());// 返回到首页
                } else {
                    mWebView.goBack();
                }
                return true;
            }
            if (mHtmlJsInteraction != null && mHtmlJsInteraction.isUpdatingData()) {
                showToast(getString(R.string.data_sync_ing), Toast.LENGTH_SHORT, Gravity.BOTTOM);
                return true;
            }
            if (mLastClickBackTimestamp <= 0 || System.currentTimeMillis() - mLastClickBackTimestamp >= 2000) {
                showToast(getString(R.string.click_again_to_exit_app), Toast.LENGTH_SHORT, Gravity.BOTTOM);
                mLastClickBackTimestamp = System.currentTimeMillis();
                return true;
            }
            finish();
            CustomApp.self.exitApp();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyWebView();
        if (mHtmlJsInteraction != null) {
            mHtmlJsInteraction.release();
            mHtmlJsInteraction = null;
        }
        mHandler.removeCallbacksAndMessages(null);
//        removeLocationListener();
    }

    /**
     * 销毁WebView
     */
    private void destroyWebView() {
        if (mWebView != null) {
            mWebView.clearCache(true);
            mWebView.clearHistory();
            mWebView.loadUrl("about:blank");
            mWebView.removeAllViews();
            mWebView.destroy();
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView = null;
        }
    }

//    /**
//     * 检测系统的GPS定位是否可用
//     *
//     * @return true 已经开启；false 不可用，提示用户去开启
//     */
//    private boolean checkGPSEnabled() {
//        List<String> providers = null;
//        if (mLocationManager == null) {
//            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//            if (mLocationManager != null) {
//                providers = mLocationManager.getAllProviders();
//            }
//        }
//        if (providers != null && providers.contains(LocationManager.GPS_PROVIDER) && !mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//            new AlertDialog.Builder(MainActivity.this)
//                    .setTitle(R.string.gps_location)
//                    .setMessage(R.string.open_gps_tips)
//                    .setCancelable(false)
//                    .setPositiveButton(R.string.go_settings, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int id) {
//                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//                            startActivityForResult(intent, mReqGPSSettingsCode);
//                        }
//                    }).create().show();
//            return false;
//        }
//        return true;
//    }
//
//    /**
//     * 获取当前的位置信息
//     */
//    private void getCurrentLocation() {
//        if (checkLocationPermissions() || !checkGPSEnabled()) {
//            return;
//        }
//        if (mLocationClient == null) {
//            mLocationClient = new LocationClient(getApplicationContext());
//            LocationClientOption option = new LocationClientOption();
//
//            //可选，设置定位模式，默认高精度
//            //LocationMode.Hight_Accuracy：高精度；
//            //LocationMode. Battery_Saving：低功耗；
//            //LocationMode. Device_Sensors：仅使用设备；
//            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//
//            //可选，设置返回经纬度坐标类型，默认gcj02
//            // gcj02：国测局坐标；
//            //bd09ll：百度经纬度坐标；
//            //bd09：百度墨卡托坐标；
//            //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标
//            option.setCoorType("bd09ll");
//
//            //可选，设置发起定位请求的间隔，int类型，单位ms
//            //如果设置为0，则代表单次定位，即仅定位一次，默认为0
//            //如果设置非0，需设置1000ms以上才有效
////                option.setScanSpan(1000);
//
//            //可选，设置是否使用gps，默认false
//            //使用高精度和仅用设备两种定位模式的，参数必须设置为true
//            option.setOpenGps(true);
//
//            //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false
////                option.setLocationNotify(true);
//
//            //可选，定位SDK内部是一个service，并放到了独立进程。
//            //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)
//            option.setIgnoreKillProcess(false);
//
//            //可选，设置是否收集Crash信息，默认收集，即参数为false
//            option.SetIgnoreCacheException(false);
//
//            //可选，7.2版本新增能力
//            //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位
////                option.setWifiCacheTimeOut(5 * 60 * 1000);
//
//            //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false
////                option.setEnableSimulateGps(false);
//
//            //可选，是否需要地址信息，默认为不需要，即参数为false
//            //如果开发者需要获得当前点的地址信息，此处必须为true
////            option.setIsNeedAddress(true);
//
//            mLocationClient.setLocOption(option);
//        }
//        if (mBDLocationListener == null) {
//            mBDLocationListener = new CustomBDLocationListener();
//            mLocationClient.registerLocationListener(mBDLocationListener);
//        }
//        if (!mLocationClient.isStarted()) {
//            mLocationClient.start();
//        } else {
//            mLocationClient.requestLocation();// 请求定位，异步返回，结果在locationListener中获取.
//        }
//        if (mLocationDialog == null) {
//            mLocationDialog = new CustomLocationDialog();
//        } else if (mLocationDialog.isAdded() && !mLocationDialog.isRemoving()) {
//            mLocationDialog.dismiss();
//        }
//        mLocationDialog.show(getSupportFragmentManager(), null);
//    }
//
//    /**
//     * 百度地图的定位监听
//     */
//    private class CustomBDLocationListener extends BDAbstractLocationListener {
//
//        @Override
//        public void onReceiveLocation(BDLocation location) {
//            double longitude = location.getLongitude();//获取经度信息
//            double latitude = location.getLatitude();//获取纬度信息
//            LogUtils.d(TAG, "onReceiveLocation() loc = [" + longitude + "," + latitude +
//                    "], radius = " + location.getRadius() + ", addr = " + Utils.checkNull(location.getAddrStr()));
//            if (mLocationDialog != null && mLocationDialog.isAdded() && !mLocationDialog.isRemoving()) {
//                mLocationDialog.locationCompleted(getString(R.string.location_succeed));
//            }
//            mWebView.loadUrl(mBaseUrl + mUrlPathInvestigation + "?timeStamp=" + System.currentTimeMillis() + "&lon=" + longitude + "&lat=" + latitude);
//        }
//    }
//
//    /**
//     * 移除位置监听器
//     */
//    private void removeLocationListener() {
//        if (mLocationClient != null) {
//            if (mBDLocationListener != null) {
//                mLocationClient.unRegisterLocationListener(mBDLocationListener);
//                mBDLocationListener = null;
//            }
//            mLocationClient.stop();
//            mLocationClient = null;
//        }
//    }

}
